package br.com.app.jsf;

import javax.faces.application.Application;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import br.com.app.mb.Sessao;

public class Autenticar implements PhaseListener{

	@Override
	public void afterPhase(PhaseEvent arg0) {
	}

	@Override
	public void beforePhase(PhaseEvent arg0) {
		FacesContext context = FacesContext.getCurrentInstance();
		if(context.getViewRoot()!=null){
			String viewId = context.getViewRoot().getViewId();
			Application app = context.getApplication();
	        Sessao sessao = (Sessao) app.evaluateExpressionGet(context,"#{sessao}",Sessao.class);
	        if(!viewId.equals("/usuario/editarUI.xhtml")&&!viewId.equals("/login.xhtml")){
	        	if(!viewId.equals("/indice.xhtml")&&sessao!=null&&sessao.getUsuario()==null){
					ViewHandler viewHandler = app.getViewHandler();
		            UIViewRoot viewRoot = viewHandler.createView(context,"/login.xhtml");
		            context.setViewRoot(viewRoot);
				}
	        }
		}
	}

	@Override
	public PhaseId getPhaseId() {
	    return PhaseId.ANY_PHASE; 
	}

}
